package com.example.springboot.service;

import com.example.springboot.entity.Admin;
import com.example.springboot.entity.Merchant;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.AdminMapper;
import com.example.springboot.mapper.MerchantMapper;
import com.example.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private AdminMapper adminMapper;



    // 用于存储验证码及其过期时间
    private Map<String, String> verificationCodes = new HashMap<>();
    private Map<String, Long> verificationCodeTimestamps = new HashMap<>();

    // 验证码有效期，单位为秒
    private static final long CODE_EXPIRATION_TIME = TimeUnit.MINUTES.toMillis(60);

    public Object loginOrRegister(String phoneNumber, String password, String role) {
        switch (role.toLowerCase()) {
            case "user":
                return handleUser(phoneNumber, password);
            case "merchant":
                return handleMerchant(phoneNumber, password);
            case "admin":
                return handleAdminLogin(phoneNumber, password);
            default:
                throw new IllegalArgumentException("无效的用户角色: " + role);
        }
    }
    // 生成并发送验证码
    public String sendPasswordResetCode(String phoneNumber, String role) {
        String resetCode = UUID.randomUUID().toString().substring(0, 6); // 生成6位数的验证码

        // 查找用户或商家
        if ("user".equalsIgnoreCase(role)) {
            User user = userMapper.findByPhoneNumber(phoneNumber);
            if (user == null) {
                throw new IllegalArgumentException("用户不存在");
            }
        } else if ("merchant".equalsIgnoreCase(role)) {
            Merchant merchant = merchantMapper.findByPhoneNumber(phoneNumber);
            if (merchant == null) {
                throw new IllegalArgumentException("商家不存在");
            }
        } else {
            throw new IllegalArgumentException("无效的角色");
        }

        // 保存验证码和时间戳
        verificationCodes.put(phoneNumber + role, resetCode);
        verificationCodeTimestamps.put(phoneNumber + role, System.currentTimeMillis());

        // 直接返回验证码给后台
        return resetCode; // 返回生成的验证码
    }



    // 验证验证码
    public boolean verifyCode(String phoneNumber, String role, String verificationCode) {
        String key = phoneNumber + role;

        // 检查验证码是否存在且未过期
        if (verificationCodes.containsKey(key)) {
            String storedCode = verificationCodes.get(key);
            long timestamp = verificationCodeTimestamps.get(key);
            long currentTime = System.currentTimeMillis();

            // 验证码是否过期
            if (currentTime - timestamp > CODE_EXPIRATION_TIME) {
                verificationCodes.remove(key);  // 移除过期的验证码
                verificationCodeTimestamps.remove(key);
                throw new IllegalArgumentException("验证码已过期");
            }

            // 验证验证码是否匹配
            if (storedCode.equals(verificationCode)) {
                return true;
            } else {
                throw new IllegalArgumentException("验证码错误");
            }
        } else {
            throw new IllegalArgumentException("验证码不存在或已过期");
        }
    }


    // 重置密码
    public String resetPassword(String phoneNumber, String role, String verificationCode, String newPassword) {
        // 验证验证码
        if (!verifyCode(phoneNumber, role, verificationCode)) {
            throw new IllegalArgumentException("验证码无效");
        }

        String hashedPassword = BCrypt.hashpw(newPassword, BCrypt.gensalt());

        switch (role.toLowerCase()) {
            case "user":
                User user = userMapper.findByPhoneNumber(phoneNumber);
                if (user == null) {
                    throw new IllegalArgumentException("用户不存在");
                }
                user.setPasswordHash(hashedPassword);
                userMapper.updateUserPassword(user);
                break;
            case "merchant":
                Merchant merchant = merchantMapper.findByPhoneNumber(phoneNumber);
                if (merchant == null) {
                    throw new IllegalArgumentException("商家不存在");
                }
                merchant.setPasswordHash(hashedPassword);
                merchantMapper.updateMerchant(merchant);
                break;
            default:
                throw new IllegalArgumentException("无效的角色");
        }

        // 密码重置成功，清除验证码
        verificationCodes.remove(phoneNumber + role);
        verificationCodeTimestamps.remove(phoneNumber + role);

        return "密码已成功重置。";
    }

    private Object handleUser(String phoneNumber, String password) {
        User user = userMapper.findByPhoneNumber(phoneNumber);
        if (user != null) {
            return verifyPassword(user.getPasswordHash(), password, user);
        }
        return registerUser(phoneNumber, password);
    }

    private User registerUser(String phoneNumber, String password) {
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        User newUser = new User();
        newUser.setPhoneNumber(phoneNumber);
        newUser.setPasswordHash(hashedPassword);
        newUser.setUsername("user_" + UUID.randomUUID().toString().substring(0, 8));
        newUser.setAvatarUrl("https://ljh-12181224.oss-cn-beijing.aliyuncs.com/413aa615-3fd0-4855-a3dc-5ec6a35eb610.jpg" + UUID.randomUUID());

        userMapper.insertUser(newUser);

        User insertedUser = userMapper.findByPhoneNumber(phoneNumber);
        if (insertedUser == null) {
            throw new IllegalStateException("用户插入失败");
        }
        return insertedUser;
    }

    private Object handleMerchant(String phoneNumber, String password) {
        Merchant merchant = merchantMapper.findByPhoneNumber(phoneNumber);
        if (merchant != null) {
            return verifyPassword(merchant.getPasswordHash(), password, merchant);
        }
        return registerMerchant(phoneNumber, password);
    }

    private Merchant registerMerchant(String phoneNumber, String password) {
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        Merchant newMerchant = new Merchant();
        newMerchant.setContactNumber(phoneNumber);
        newMerchant.setPasswordHash(hashedPassword);
        newMerchant.setName("merchant_" + UUID.randomUUID().toString().substring(0, 8));
        newMerchant.setAvatarUrl("https://ljh-12181224.oss-cn-beijing.aliyuncs.com/413aa615-3fd0-4855-a3dc-5ec6a35eb610.jpg" + UUID.randomUUID());

        merchantMapper.insertMerchant(newMerchant);

        Merchant insertedMerchant = merchantMapper.findByPhoneNumber(phoneNumber);
        if (insertedMerchant == null) {
            throw new IllegalStateException("注册失败");
        }
        return insertedMerchant;
    }

    private Object handleAdminLogin(String username, String password) {
        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) {
            throw new IllegalArgumentException("管理员不存在");
        }
        return verifyPassword(admin.getPasswordHash(), password, admin);
    }
    private Object verifyPassword(String hashedPassword, String inputPassword, Object userOrMerchantOrAdmin) {
        if (hashedPassword == null || hashedPassword.isEmpty()) {
            throw new IllegalArgumentException("密码无效或为空");
        }
        if (!BCrypt.checkpw(inputPassword, hashedPassword)) {
            throw new IllegalArgumentException("密码错误");
        }
        return userOrMerchantOrAdmin;
    }


}
